package com.fenqile.pop.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Date;


/** 
 * @author  arvin 
 * @date 创建时间：2017年5月25日下午12:43:41
 * 类说明 
 */

public class PopApiDemo
{
	private static String server_url = "http://pop.api.fenqile.com/router/rest.json";
	private static String partner_id = "PAI201605260000003";
	private static String partner_key = "4f13adc14ef9c5f32fb49e8a829c443a";
	private static String method = "fenqile.trades.list.get";
	
	public static void main(String[] args) throws Exception {
		
		new Thread(new Starter()).start();
		new Thread(new Starter()).start();
		
	}
	
	public static class Starter implements Runnable {

		@Override
		public void run() {
			for (int i=10; i>0; i--) {
				try {
					start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public static void start() throws Exception
	{
		//时间戳
		long timestamp = new Date().getTime()/1000;
		
		//系统参数,参数顺序无关
		String systemParams = ""
				+ "timestamp="+timestamp
				+ "&format=json"
				+ "&partner_id="+PopApiDemo.partner_id
				+ "&method=" + PopApiDemo.method
				+ "&v=1.4"
				;
		//应用参数，参数顺序无关
		String appParams = "begin_time=2017-08-10 10:00:01&end_time=2017-08-11 10:00:01&fields=order_id,sku_id,sku_pic";
		
		
		//1、系统参数+应用参数，按字符串排序; 2、最后附上partner_key
		String params = "begin_time=2017-08-10 10:00:01"
				+ "&end_time=2017-08-11 10:00:01" 
				+ "&fields=order_id,sku_id,sku_pic"
				+ "&format=json"
				+ "&method="+ PopApiDemo.method
				+ "&partner_id="+PopApiDemo.partner_id
				+ "&timestamp="+timestamp
				+ "&v=1.4" 
				+ "&partner_key=" + PopApiDemo.partner_key;
		
		//计算sign
		System.out.println(params);
		
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte [] bytes = md5.digest(params.getBytes());
		String sign = bytesToHex(bytes);
		
		System.out.println(sign);
		
		//Get方式
		String request = systemParams + "&" + appParams + "&sign=" + sign;
		System.out.println("GET URL:" + request);
		String response1 = sendGet(PopApiDemo.server_url,request);	
		System.out.println(response1);
		//Post方式
		String postUrl = PopApiDemo.server_url + "?" + "sign="+sign + "&" + systemParams;
		System.out.println("POST URL:" + postUrl);
		String response2 = sendPost(postUrl,appParams);
		System.out.println(response2);
		
	}
	
	
	public static String bytesToHex(byte buf[]) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < buf.length; i++) {  
            String hex = Integer.toHexString(buf[i] & 0xFF);  
            if (hex.length() == 1) {  
                hex = '0' + hex;  
            }  
            sb.append(hex.toLowerCase());  
        }  
        return sb.toString();  
    }  
	
	
	public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            
            System.out.println(urlNameString);
            
            //建立连接
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.connect();
            
            //读取结果
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                
            }
        }
        return result;
    }
	
	 public static String sendPost(String url, String param) {
	        PrintWriter out = null;
	        BufferedReader in = null;
	        String result = "";
	        try {
	            URL realUrl = new URL(url);
	            URLConnection conn = realUrl.openConnection();
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            out = new PrintWriter(conn.getOutputStream());
	            out.print(param);
	            out.flush();
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送 POST 请求出现异常！"+e);
	            e.printStackTrace();
	        }
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }    
	

}
